package com.rivercloud.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.exceptions.IbatisException;

import com.rivercloud.dao.Impl.UserDaoImpl;
import com.rivercloud.entity.Permission;
import com.rivercloud.entity.Role;
import com.rivercloud.entity.User;
import com.rivercloud.entity.UserVo;

public class MyFilter implements Filter {

	
	private static List<UserVo>  urpVO=new ArrayList<UserVo>();
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
			List<User> list = new UserDaoImpl().query_user_role_permission_all1(null);
		for (User user : list) {
			UserVo userVo = new UserVo();
			userVo.setuId(user.getId());
			userVo.setuName(user.getName());
			List<Role> roles = user.getRoles();
			Iterator<Role> iterator = roles.iterator();
			StringBuffer sb=new StringBuffer();
			while (iterator.hasNext()) {
				Role role = iterator.next();
				sb.append(role.getId()+",");
				List<Permission> permissions = role.getPermissions();
				Iterator<Permission> iterator2 = permissions.iterator();
				StringBuffer sbPid=new StringBuffer();
				StringBuffer sbKeyword=new StringBuffer();
				while(iterator2.hasNext()){
					Permission permission = iterator2.next();
					sbPid.append(permission.getId()+",");
					sbKeyword.append(permission.getKeyword()+",");
				}
				sbPid.replace(sbPid.lastIndexOf(","), sbPid.lastIndexOf(",")+1, "");
				sbKeyword.replace(sbKeyword.lastIndexOf(","), sbKeyword.lastIndexOf(",")+1, "");
				userVo.setpId(sbPid.toString());
				userVo.setpKeyword(sbKeyword.toString());
			}
			
			sb.replace(sb.lastIndexOf(","), sb.lastIndexOf(",")+1, "");
			userVo.setrId(sb.toString());
			urpVO.add(userVo);
			
		}
			
			System.out.println(Arrays.toString(urpVO.toArray(new UserVo[0])));
		
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		((HttpServletRequest)request).getSession().setAttribute("urpVO", urpVO);
		
		
		
		
		chain.doFilter(request, response);
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	
	

		
		

	
	

}
